/*
 * @Author: qianmingtian
 * @Date: 2020-07-17 11:18:43
 * @LastEditors: qianmingtian
 * @LastEditTime: 2020-07-17 17:55:33
 * @FilePath: \qianmingtian.github.io\code\java\MultiThread\exam\exam03\ExamThreadSynchronized03.java
 */
package MultiThread.exam.exam03;

/**
 * 题目：doother方法需要等待dosome方法结束吗？
 * 
 * 不需要 这里的 有两把锁
 * 
 * doSome begin doSome end do Other begin do other end
 */
public class ExamThreadSynchronized03 {

    public static void main(String[] args) throws InterruptedException {
        MyClass myClass1 = new MyClass();
        MyClass myClass2 = new MyClass();

        Thread t1 = new MyThread(myClass1);

        Thread t2 = new MyThread(myClass2);

        t1.setName("t1");
        t2.setName("t2");

        t1.start();

        Thread.sleep(1000);

        t2.start();
    }

}

/**
 * 这里的synchrinized 锁住的是 this 对象的dosome 方法，doother方法没有锁 , 所以不需要等待dosome方法结束
 */
class MyClass {  

    public synchronized void doSome() {
        System.out.println("doSome begin");

        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("doSome end");

    }

    public synchronized void doOther() {
        System.out.println("do Other begin");

        System.out.println("do other end");
    }
}

class MyThread extends Thread {

    private MyClass myClass;

    MyThread(MyClass myClass) {
        this.myClass = myClass;
    }

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("t1")) {
            myClass.doSome();
        }
        if (Thread.currentThread().getName().equals("t2")) {
            myClass.doOther();
        }

    }

}
